package utils

import (
	"database/sql"
	"fmt"

	"github.com/go-sql-driver/mysql"
)

// MakeSureDBExist 确认一个Mysql数据库存在
func MakeSureDBExist(username, passwd, host string, port int, dbname string) error {
	connString := fmt.Sprintf(`%v:%v@tcp(%v:%v)/?charset=utf8mb4`, username, passwd, host, port)
	db, err := sql.Open(`mysql`, connString)
	if err != nil {
		return err
	}
	_, err = db.Exec("use " + dbname + ";")
	if err != nil {
		sqlerr, ok := err.(*mysql.MySQLError)
		if !ok {
			return err
		}
		if sqlerr.Number != 1049 {
			return err
		}
		_, err := db.Exec("create database " + dbname + ` charset=utf8mb4;`)
		if err != nil {
			return err
		}
	}
	return nil
}
